package com.groupbuying.store.service.impl;

import com.groupbuying.store.connector.SysconfigFeign;
import com.groupbuying.store.constants.CommonConstants;
import com.groupbuying.store.constants.StoreMainInfoEnumConstants;
import com.groupbuying.store.context.FilterContextHandler;
import com.groupbuying.store.dao.StoreMainInfoDao;
import com.groupbuying.store.domain.*;
import com.groupbuying.store.dto.forExternal.StoreMainDTO;
import com.groupbuying.store.dto.forExternal.do2dto.StoreMainInfoConvert;
import com.groupbuying.store.dto.forManage.StoreCheckoutCounterRelDTO;
import com.groupbuying.store.pojo.StoreCheckoutCounterRelEnum;
import com.groupbuying.store.pojo.StoreMainInfoEnum;
import com.groupbuying.store.pojo.StoreShopEnum;
import com.groupbuying.store.service.*;
import com.groupbuying.store.utils.*;
import com.groupbuying.store.utils.apiresult.ApiResult;
import com.groupbuying.store.utils.apiresult.ApiResultCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @anthor wenguoqiang
 * @date: 2019/01/24 10:18
 * @company 够样
 * @des
 **/
@Service
@Transactional
public class ChainStoresApiServiceImpl implements ChainStoresApiService {


    @Autowired
    private StoreAccountService storeAccountService;
    @Autowired
    private StoreAccountShopRelService storeAccountShopRelService;
    @Autowired
    private StoreMainInfoService storeMainInfoService;
    @Autowired
    private StoreCheckoutCounterService storeCheckoutCounterService;
    @Autowired
    private StoreCheckoutCounterRelService storeCheckoutCounterRelService;

    @Autowired
    @Lazy
    private StoreCapitalVirtualAccountService storeCapitalVirtualAccountService;

    @Autowired
    private StoreShopService storeShopService;

    @Autowired
    private StoreCompanyInfoService storeCompanyInfoService;

    @Autowired
    private CompanyQualificationService storeCompanyQualificationService;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private GeoShopInfoService geoShopInfoService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private StoreMainInfoDao storeMainInfoDao;


    @Override
    public R getCheckoutCounterList(Map<String, Object> mapParams) {
        String providerId = FilterContextHandler.getName();
        mapParams.put("providerId", providerId);
        mapParams.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        mapParams.put("sort", "counter.createopetime");
        mapParams.put("order", "desc");

        Query query = new Query(mapParams);
        List<StoreCheckoutCounterRelDTO> list = storeCheckoutCounterRelService.getListByAccountId(query);
        int total = storeCheckoutCounterRelService.getListCountByAccountId(query);

        PageUtils pageUtil = new PageUtils(list, total);
        return R.ok().put("page", pageUtil);
    }

    @Transactional
    @Override
    public R saveStoreCheckoutCounter(Map<String, Object> mapParams) {
        // 解析map参数
        // 门店uuid
        Object temp = mapParams.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        // 款台名称
        temp = mapParams.get("counterName");
        String counterName = temp != null ? temp.toString() : null;
        // 是否有效 1有效 2.无效
        temp = mapParams.get("isValid");
        String isValid = temp != null ? temp.toString() : null;
        //员工编号
        temp = mapParams.get("staffUuid");
        String staffUuid = temp != null ? temp.toString() : null;

        String accountId = FilterContextHandler.getUserID();
        String providerId = FilterContextHandler.getName();

        if (StringUtils.isBlank(storeUuid) || StringUtils.isBlank(counterName) || StringUtils.isBlank(isValid) || StringUtils.isBlank(staffUuid)) {
            return R.error();
        }

        if(!redisUtils.setIfAbsent(storeUuid+staffUuid,"",10L)){
            return R.ok();
        }

        // 新建收银台
        String time = DateFormatHelper.getNowTimeStr();
        StoreCheckoutCounterDO storeCheckoutCounter = new StoreCheckoutCounterDO();
        String counterUuid = sysconfigFeign.getUuidByLeaf();

        // 生成小程序码
        Map<String, String> fileGroupKeys = storeCheckoutCounterService.saveCounterUnlimited(counterUuid);

        storeCheckoutCounter.setUuid(counterUuid);
        storeCheckoutCounter.setDelflag(CommonConstants.COMMON_FLAG_UNDEL);
        storeCheckoutCounter.setCounterno(sysconfigFeign.getCounterNoByLeaf());
        storeCheckoutCounter.setStoreuuid(storeUuid);
        storeCheckoutCounter.setCountername(counterName);
        storeCheckoutCounter.setIsvalid(isValid);
        storeCheckoutCounter.setOpetime(time);
        storeCheckoutCounter.setCreateopetime(time);
        storeCheckoutCounter.setOper(accountId);
        storeCheckoutCounter.setCreateoper(accountId);
        storeCheckoutCounter.setVersion(0);
        storeCheckoutCounter.setWxacode(fileGroupKeys.get("payPage"));
        storeCheckoutCounter.setGywxacode(fileGroupKeys.get("paygyPage"));
        storeCheckoutCounterService.save(storeCheckoutCounter);

        // 收银台和门店绑定
        StoreCheckoutCounterRelDO newStoreCheckoutCounterRel = new StoreCheckoutCounterRelDO();
        newStoreCheckoutCounterRel.setUuid(sysconfigFeign.getUuidByLeaf());
        newStoreCheckoutCounterRel.setCounteruuid(storeCheckoutCounter.getUuid());
        newStoreCheckoutCounterRel.setStaffuuid(staffUuid);
        newStoreCheckoutCounterRel.setBegintime(time);
        newStoreCheckoutCounterRel.setState(StoreCheckoutCounterRelEnum.STATE_NOW);
        newStoreCheckoutCounterRel.setOpetime(time);
        newStoreCheckoutCounterRel.setCreateopetime(time);
        newStoreCheckoutCounterRel.setOper(accountId);
        newStoreCheckoutCounterRel.setCreateoper(accountId);
        newStoreCheckoutCounterRel.setVersion(0);
        newStoreCheckoutCounterRel.setDelflag(CommonConstants.COMMON_FLAG_UNDEL);
        storeCheckoutCounterRelService.save(newStoreCheckoutCounterRel);

        // 员工与门店绑定
        StoreAccountShopRelDO storeAccountShopRelDO = new StoreAccountShopRelDO();
        // 绑定员工账号
        storeAccountShopRelDO.setAccountId(staffUuid);
        storeAccountShopRelDO.setUuid(sysconfigFeign.getUuidByLeaf());
        storeAccountShopRelDO.setDelFlag(CommonConstants.COMMON_FLAG_UNDEL);
        storeAccountShopRelDO.setStoreUuid(storeUuid);
        storeAccountShopRelDO.setProviderId(providerId);
        storeAccountShopRelDO.setOpeTime(time);
        storeAccountShopRelDO.setCreateOpeTime(time);
        storeAccountShopRelDO.setOper(accountId);
        storeAccountShopRelDO.setCreateOper(accountId);
        storeAccountShopRelService.save(storeAccountShopRelDO);


        return R.ok();

    }
    @Override
    public R getStoreByProviderId(Map<String, Object> params) {
        try {
            params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
            // 服务商id
            params.put("chainstoresuuid", FilterContextHandler.getName());
            params.put("sort", "createOpeTime");
            params.put("order", "desc");
            Query query = new Query(params);
            // TODO: 缺少DTO
            /* List<StoreMainInfoDO> list = storeMainInfoService.getStoreListByProviderIdAndAccountId(query);
        int total = storeMainInfoService.getStoreListByProviderIdAndAccountIdCount(query);*/
            List<StoreMainInfoDO> list = storeMainInfoService.list(query);
            List<StoreMainDTO> dtos = new ArrayList<StoreMainDTO>(list.size());
            for (StoreMainInfoDO storeMainInfoDO : list) {
                switch (storeMainInfoDO.getAuditstatus()) {
                    case StoreMainInfoEnum.AUDIT_UNDONE: {
                        storeMainInfoDO.setAuditstatus("审核中");
                    }
                    break;
                    case StoreMainInfoEnum.BUSINESS_AUDIT_PASS: {
                        storeMainInfoDO.setAuditstatus("业务人员审核通过");
                    }
                    break;
                    case StoreMainInfoEnum.AUDIT_NO_PASS: {
                        storeMainInfoDO.setAuditstatus("审核驳回");
                    }
                    break;
                    case StoreMainInfoEnum.REPORT_UNDONE: {
                        storeMainInfoDO.setAuditstatus("报备失败");
                    }
                    break;
                    case StoreMainInfoEnum.FINANCE_AUDIT_PASS: {
                        storeMainInfoDO.setAuditstatus("财务人员审核通过");
                    }
                    break;
                }
                StoreCompanyInfoDO storeCompanyInfoDO = storeCompanyInfoService.getCompanyInfoByStoreUuid(storeMainInfoDO.getUuid());
                StoreMainDTO storeMainDTO = StoreMainInfoConvert.MAPPER.doToDTO(storeMainInfoDO);
                storeMainDTO.setCompanytype(storeCompanyInfoDO.getCompanytype());
                dtos.add(storeMainDTO);
            }
            int total = storeMainInfoService.count(query);
            PageUtils pageUtil = new PageUtils(dtos, total);
            return R.ok().put("page", pageUtil);
        } catch (Exception e) {
            return R.error();
        }
    }

    @Override
    public R getCrossStoreByProviderId(Map<String, Object> params) {
        try {
            params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
            // 服务商id
            params.put("chainstoresuuid", FilterContextHandler.getName());
            params.put("auditstatus", StoreMainInfoEnum.BUSINESS_AUDIT_PASS);
            params.put("freezestatus", StoreMainInfoEnum.UNFROZEN);
            Query query = new Query(params);
            List<StoreMainInfoDO> list = storeMainInfoService.list(query);
            int total = storeMainInfoService.count(query);
            PageUtils pageUtil = new PageUtils(list, total);
            return R.ok().put("page", pageUtil);
        } catch (Exception e) {
            return R.error();
        }
    }

    @Transactional
    @Override
    public R addChildStore(Map<String, Object> mapParams) {
        //店铺名称
        Object temp = mapParams.get("storeName");
        String storeName = temp != null ? temp.toString() : null;
        //分类uuid
        temp = mapParams.get("catetoryUuid");
        String catetoryUuid = temp != null ? temp.toString() : null;
        //人均消费
        temp = mapParams.get("consumption");
        String consumption = temp != null ? temp.toString() : null;
        //省
        temp = mapParams.get("province");
        String province = temp != null ? temp.toString() : null;
        //市
        temp = mapParams.get("city");
        String city = temp != null ? temp.toString() : null;
        //区
        temp = mapParams.get("region");
        String region = temp != null ? temp.toString() : null;
        //门店详细地址
        temp = mapParams.get("realDetailAddress");
        String realDetailAddress = temp != null ? temp.toString() : null;
        //门店详细地址
        temp = mapParams.get("detailAddress");
        String detailAddress = temp != null ? temp.toString() : null;
        //门店联系人电话
        temp = mapParams.get("contactman");
        String contactman = temp != null ? temp.toString() : null;
        //step2
        //法人名称
        temp = mapParams.get("legalPerson");
        String legalPerson = temp != null ? temp.toString() : null;

        //法人证件类型 00-身份证
        // temp = mapParams.get("documentType");
        String documentType = "00";
        //法人身份证编号
        temp = mapParams.get("legalId");
        String legalId = temp != null ? temp.toString() : "";
        //法人证件有效期
        temp = mapParams.get("legalidTime");
        String legalidTime = temp != null ? temp.toString() : "";
        //法人身份证件正面
        temp = mapParams.get("Legalidcard1");
        String legalidcard1 = temp != null ? temp.toString() : "";
        //法人身份证件反面
        temp = mapParams.get("Legalidcard2");
        String legalidcard2 = temp != null ? temp.toString() : "";
        //营业执照编号
        temp = mapParams.get("bussinessLicense");
        String bussinessLicense = temp != null ? temp.toString() : "";
        //营业执照有效日期
        temp = mapParams.get("bussinessLicenseTime");
        String bussinessLicenseTime = temp != null ? temp.toString() : "";
        //营业执照复印件
        temp = mapParams.get("bussinessLicensePhoto");
        String bussinessLicensePhoto = temp != null ? temp.toString() : "";
        //客户协议书
        temp = mapParams.get("agreementimage");
        String agreementimage = temp != null ? temp.toString() : "";
        //结算银行卡正面
        temp = mapParams.get("settle1image");
        String settle1image = temp != null ? temp.toString() : "";
        //结算银行卡反面
        temp = mapParams.get("settle2image");
        String settle2image = temp != null ? temp.toString() : "";
        //开户许可证或印鉴卡
        temp = mapParams.get("licenseimage");
        String licenseimage = temp != null ? temp.toString() : "";

        //结算方式
        //temp = mapParams.get("settleType");
        String settleType = temp != null ? temp.toString() : null;

        //step3
        //企业信息
        //企业名称
        temp = mapParams.get("companyName");
        String companyName = temp != null ? temp.toString() : null;
        //注册资金
        //temp = mapParams.get("registermoney");
        //String registermoney = temp != null ? temp.toString() : null;
        //企业类型
        temp = mapParams.get("companyType");
        String companyType = temp != null ? temp.toString() : null;
        //所属行业
        temp = mapParams.get("saletype");
        String saletype = temp != null ? temp.toString() : null;
        //企业所在省
        temp = mapParams.get("companyInfoProvince");
        String companyInfoProvince = temp != null ? temp.toString() : null;
        //企业所在市
        temp = mapParams.get("companyInfoCity");
        String companyInfoCity = temp != null ? temp.toString() : null;
          //企业所在地址
        temp = mapParams.get("companyInfoAddress");
        String companyInfoAddress = temp != null ? temp.toString() : null;
        //企业所在省
       /* String companyInfoProvince = province;
        //企业所在市
        String companyInfoCity = city;*/
        //企业所在地址
        //String companyInfoAddress = detailAddress;
        //银行账户
        temp = mapParams.get("companyAccountNo");
        String companyAccountNo = temp != null ? temp.toString() : null;
        //银行开户名
        temp = mapParams.get("openAccountName");
        String openAccountName = temp != null ? temp.toString() : null;
        //银行账户类型  0 个人银行卡   1 是个人信用卡  2 对公账号
        temp = mapParams.get("accoutType");
        String accoutType = temp != null ? temp.toString() : "";
        // 开户银行详细名称
        temp = mapParams.get("bankName");
        String bankName = temp != null ? temp.toString() : null;
        //开户行支行名称
        temp = mapParams.get("openAccountBankName");
        String openAccountBankName = temp != null ? temp.toString() : null;
        //银行所在省
        temp = mapParams.get("bankProvinceName");
        String bankProvinceName = temp != null ? temp.toString() : null;
        //银行所在市
        temp = mapParams.get("bankCityName");
        String bankCityName = temp != null ? temp.toString() : null;
        //银行卡类型
        temp = mapParams.get("bankCardType");
        String bankCardType = temp != null ? temp.toString() : null;
        //银行卡身份证号
        temp = mapParams.get("bankPeopleId");
        String bankPeopleId = temp != null ? temp.toString() : null;
        //银行预留手机号
        temp = mapParams.get("bankMobile");
        String bankMobile = temp != null ? temp.toString() : null;
        //商户 账户 --手机号码
       /* temp = mapParams.get("mobile");
        String mobile = temp != null ? temp.toString() : "";*/
        String mobile = contactman;

        //法人手机号
        //temp = mapParams.get("legalMobile");
        //String legalMobile = temp != null ? temp.toString() : "";
        String legalMobile = bankMobile;

        //组织机构代码
        temp = mapParams.get("organizationcode");
        String organizationcode = temp != null ? temp.toString() : "";
        //组织机构证件照
        temp = mapParams.get("organizationphoto");
        String organizationphoto = temp != null ? temp.toString() : "";
        //门头照
        temp = mapParams.get("imageKey");
        String imageKey = temp != null ? temp.toString() : null;
        //内景照
        temp = mapParams.get("imageKeytwo");
        String imageKeytwo = temp != null ? temp.toString() : null;
        /**
         * 纬度
         */
        temp = mapParams.get("latitude");
        String latitude = temp != null ? temp.toString() : null;
        /**
         * 经度
         */
        temp = mapParams.get("longitude");
        String longitude = temp != null ? temp.toString() : null;
        /**
         * 法人授权函
         */
        temp = mapParams.get("authorizationLetter");
        String authorizationLetter = temp != null ? temp.toString() : null;
        /**
         * 结算人类型
         */
        temp = mapParams.get("settlorType");
        String settlorType = temp != null ? temp.toString() : null;
        /**
         * 商户类型
         */
        temp = mapParams.get("storeType");
        String storeType = temp != null ? temp.toString() : null;
        /**
         * 轮播图
         */
        temp = mapParams.get("slideshow");
        String slideshow = temp != null ? temp.toString() : null;
        /**
         * 法人手持身份证
         */
        temp = mapParams.get("legalInHandCard");
        String legalInHandCard = temp != null ? temp.toString() : null;


        String userId = FilterContextHandler.getUserID();
        String providerId = FilterContextHandler.getName();

        //查询门店名称
        Map searchMap = new HashMap();
        searchMap.put("storename", storeName);
        searchMap.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        List<StoreMainInfoDO> mainInfoModelSearch = storeMainInfoService.list(searchMap);
        if (mainInfoModelSearch.size() != 0) {
            //加锁
            return R.error("店铺名称已存在");
        }

        //1.操作人信息
        StoreMainInfoDO mainInfoModel = createStoreMainInfo(userId, storeName, catetoryUuid, contactman, providerId,storeType);

        //2.设置门店信息
        StoreShopDO shopModel = createStoreShop(consumption, province, city, region, detailAddress, providerId, mobile, mainInfoModel, imageKey, imageKeytwo, latitude, longitude,slideshow,realDetailAddress);
        //2.2保存门店geocode码表
        geoShopInfoService.saveGeoShopInfo(shopModel.getUuid(), shopModel.getLat(), shopModel.getLgt());

        //3.虚拟账户资金
        createVirtualAndVirtualAccount(userId, companyAccountNo, openAccountName, accoutType, bankName, openAccountBankName, bankProvinceName, bankCityName, bankCardType, bankPeopleId, bankMobile, mobile, mainInfoModel);

        //4.创建公司信息
        StoreCompanyInfoDO companyInfo = createStoreCompanyInfo(legalPerson, contactman, legalMobile, documentType, legalId, legalidTime, legalidcard1, legalidcard2, agreementimage, settle1image, settle2image, licenseimage, companyName, companyType, companyInfoProvince, companyInfoCity, companyInfoAddress, mainInfoModel, saletype, authorizationLetter, settlorType,legalInHandCard);

        //5.创建公司资历信息
        createCompanyQualification(bussinessLicense, bussinessLicenseTime, bussinessLicensePhoto, organizationcode, organizationphoto, providerId, companyInfo);

        //6.创建用户和门店关系
        createStoreAccountShopRel(userId, providerId, mainInfoModel);


        return R.ok();
    }


    @Override
    public R addChildStoreAgain(Map<String, Object> mapParams) {
        //连锁门店uuid
        Object temp = mapParams.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        //店铺名称
        temp = mapParams.get("storeName");
        String storeName = temp != null ? temp.toString() : null;

        //1.查询该门店，判断是否是同名提交，非同名需要先判断是否有重名在逻辑删除
        StoreMainInfoDO storeMainInfoDO = storeMainInfoService.get(storeUuid);

        if(!storeMainInfoDO.getStorename().equals(storeName)){
            //查询门店名称
            Map searchMap = new HashMap();
            searchMap.put("storename", storeName);
            searchMap.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
            List<StoreMainInfoDO> mainInfoModelSearch = storeMainInfoService.list(searchMap);
            if (mainInfoModelSearch.size() != 0) {
                //加锁
                return R.error("店铺名称已存在");
            }
        }



        storeMainInfoDO.setDelflag(CommonConstants.COMMON_FLAG_DEL);
        storeMainInfoService.update(storeMainInfoDO);

        //2.插入新数据
        return this.addChildStore(mapParams);
    }


    public void createStoreAccountShopRel(String userId, String providerId, StoreMainInfoDO mainInfoModel) {
        StoreAccountShopRelDO storeAccountShopRel = new StoreAccountShopRelDO();
        storeAccountShopRel.setUuid(sysconfigFeign.getUuidByLeaf());
        storeAccountShopRel.setDelFlag(CommonConstants.COMMON_FLAG_UNDEL);
        storeAccountShopRel.setVersion(0);
        storeAccountShopRel.setOper(userId);
        String time = DateFormatHelper.getNowTimeStr();
        storeAccountShopRel.setOpeTime(time);
        storeAccountShopRel.setCreateOpeTime(time);
        storeAccountShopRel.setAccountId(userId);
        storeAccountShopRel.setProviderId(providerId);
        storeAccountShopRel.setCreateOper(userId);
        storeAccountShopRel.setStoreUuid(mainInfoModel.getUuid());
        storeAccountShopRelService.save(storeAccountShopRel);
    }

    public StoreCompanyInfoDO createStoreCompanyInfo(String legalPerson, String contactman, String legalMobile, String documentType, String legalId, String legalidTime, String legalidcard1, String legalidcard2, String agreementimage, String settle1image, String settle2image, String licenseimage, String companyName, String companyType, String companyInfoProvince, String companyInfoCity, String companyInfoAddress, StoreMainInfoDO mainInfoModel, String saletype, String authorizationLetter, String settlorType,String legalInHandCard) {
        StoreCompanyInfoDO companyInfo = new StoreCompanyInfoDO();
        companyInfo.setUuid(sysconfigFeign.getUuidByLeaf());
        companyInfo.setDelflag(CommonConstants.COMMON_FLAG_UNDEL);
        companyInfo.setVersion(0);
        String time = DateFormatHelper.getNowTimeStr();
        companyInfo.setCreateopetime(time);
        companyInfo.setOpetime(time);
        companyInfo.setStoreuuid(mainInfoModel.getUuid());
        companyInfo.setCompanyname(companyName);
        companyInfo.setCompanytype(companyType);
        companyInfo.setContactman(contactman);
        companyInfo.setLegalperson(legalPerson);
        companyInfo.setLegalmobile(legalMobile);
        companyInfo.setLegalid(legalId);
        companyInfo.setLegalidtime(legalidTime);
        companyInfo.setLegalidcard1(legalidcard1);
        companyInfo.setLegalidcard2(legalidcard2);
        companyInfo.setDocumenttype(documentType);
        companyInfo.setProvince(companyInfoProvince);
        companyInfo.setCity(companyInfoCity);
        companyInfo.setAddress(companyInfoAddress);
        companyInfo.setSettle1image(settle1image);
        companyInfo.setSettle2image(settle2image);
        companyInfo.setLicenseimage(licenseimage);
        companyInfo.setAgreementimage(agreementimage);
        companyInfo.setSaletype(saletype);
        companyInfo.setAuthorizationletter(authorizationLetter);
        companyInfo.setSettlortype(settlorType);
        companyInfo.setLegalInHandCard(legalInHandCard);
        storeCompanyInfoService.save(companyInfo);
        return companyInfo;
    }

    public void createCompanyQualification(String bussinessLicense, String bussinessLicenseTime, String bussinessLicensePhoto, String organizationcode, String organizationphoto, String providerId, StoreCompanyInfoDO companyInfo) {
        CompanyQualificationDO companyQualification = new CompanyQualificationDO();
        companyQualification.setUuid(sysconfigFeign.getUuidByLeaf());
        companyQualification.setCompanyuuid(companyInfo.getUuid());
        companyQualification.setVersion(0);
        companyQualification.setDelflag(CommonConstants.COMMON_FLAG_UNDEL);
        companyQualification.setCreateoper(providerId);
        companyQualification.setOper(providerId);
        String time = DateFormatHelper.getNowTimeStr();
        companyQualification.setCreateopetime(time);
        companyQualification.setOpetime(time);
        companyQualification.setBussinesslicense(bussinessLicense);
        companyQualification.setBussinesslicensetime(bussinessLicenseTime);
        companyQualification.setBussinesslicensephoto(bussinessLicensePhoto);
        companyQualification.setOrganizationcode(organizationcode);
        companyQualification.setOrganizationphoto(organizationphoto);
        storeCompanyQualificationService.save(companyQualification);
    }

    private void createVirtualAndVirtualAccount(String userId, String companyAccountNo, String openAccountName, String accoutType, String bankName, String openAccountBankName, String bankProvinceName, String bankCityName, String bankCardType, String bankPeopleId, String bankMobile, String mobile, StoreMainInfoDO mainInfoModel) {
        StoreCapitalVirtualAccountDO virtualModel = new StoreCapitalVirtualAccountDO();
        virtualModel.setCreateoper(userId);
        virtualModel.setOper(userId);
        virtualModel.setCompanyaccountno(companyAccountNo);
        virtualModel.setOpenaccountbankname(openAccountBankName);
        virtualModel.setOpenaccountname(openAccountName);
        virtualModel.setAccounttype(accoutType);
        virtualModel.setBankname(bankName);
        virtualModel.setProvincename(bankProvinceName);
        virtualModel.setCityname(bankCityName);
        virtualModel.setBankcardtype(bankCardType);
        virtualModel.setPeopleid(bankPeopleId);
        virtualModel.setMobile(bankMobile);
        virtualModel.setVirtualmoney(new BigDecimal(0));
        virtualModel.setVirtualpasswd("6583dba8186d396cbcc9a38f51d8a520");//初始密码为000000
        virtualModel.setFreezevirtualmoney(new BigDecimal(0));
        virtualModel.setCashAmount(new BigDecimal(0));
        virtualModel.setBalanceAmount(new BigDecimal(0));
        virtualModel.setIntegralAmount(new BigDecimal(0));
        //3.1 创建虚拟资金账号
        virtualModel = storeCapitalVirtualAccountService.createStoreVirtualAccount(mainInfoModel.getUuid(), mainInfoModel.getStoreno(), mainInfoModel.getStorename(), mobile, virtualModel);

    }

    private StoreShopDO createStoreShop(String consumption, String province, String city, String region, String detailAddress, String providerId, String mobile, StoreMainInfoDO mainInfoModel, String imageKey, String imageKeytwo, String latitude, String longitude,String slideshow,String realDetailAddress) {
        StoreShopDO shopModel = new StoreShopDO();
        shopModel.setShoptype(StoreMainInfoEnum.STORE_TYPE_SERVSHOP);
        shopModel.setShopname(mainInfoModel.getStorename());
        shopModel.setProvince(province);
        shopModel.setCity(city);
        shopModel.setRegion(region);
        shopModel.setConsumption(new BigDecimal(consumption));
        shopModel.setCreateoper(providerId);
        shopModel.setDetailaddress(detailAddress);
        shopModel.setTelephone(mobile);
        shopModel.setChoosedattr(realDetailAddress);
        shopModel.setUuid(sysconfigFeign.getUuidByLeaf());
        shopModel.setDelflag(CommonConstants.COMMON_FLAG_UNDEL);
        shopModel.setVersion(0);
        shopModel.setDoorphoto(imageKey);
        shopModel.setWithinphoto(imageKeytwo);
        shopModel.setStoreuuid(mainInfoModel.getUuid());
        shopModel.setShoptype(StoreShopEnum.SHOP_TYPE_SHOP);
        shopModel.setAuditstatus(StoreMainInfoEnum.BUSINESS_AUDIT_PASS);
        shopModel.setStatus(StoreShopEnum.STATUS_WATI_BUSINESS);
        shopModel.setLat(new BigDecimal(latitude));
        shopModel.setLgt(new BigDecimal(longitude));
        shopModel.setSlideshow(slideshow);
        storeShopService.save(shopModel);
        return shopModel;
    }

    private StoreMainInfoDO createStoreMainInfo(String userId, String storeName, String catetoryUuid, String contactman, String providerId,String storeType) {
        StoreMainInfoDO mainInfoModel = new StoreMainInfoDO();
        String storeUuid = sysconfigFeign.getStoreNoByLeaf();
        mainInfoModel.setUuid(storeUuid);
        mainInfoModel.setOper(userId);
        mainInfoModel.setCreateoper(userId);
        mainInfoModel.setIsadmin("");
        mainInfoModel.setEmail("");
        //设置商户类型为 1：优店商户,2：优惠买单商户,3：优惠买单并且是优店的商户
        mainInfoModel.setStoretype(storeType);
        mainInfoModel.setCreateoper(userId);
        mainInfoModel.setStorename(storeName);
        mainInfoModel.setMobile(contactman);
        mainInfoModel.setChainstoresuuid(providerId);
        mainInfoModel.setServcategory(catetoryUuid);
        mainInfoModel.setDelflag(CommonConstants.COMMON_FLAG_UNDEL);
        //设置为待提交审核
        mainInfoModel.setAuditstatus(StoreMainInfoEnum.AUDIT_UNDONE);
        //默认为激活
        mainInfoModel.setActivestate(StoreMainInfoEnum.ACTIVESTATE_YES);
        //默认为未冻结
        //mainInfoModel.setFrozensate(StoreMainInfoEnum.UNFROZEN);
        mainInfoModel.setFreezestatus(StoreMainInfoEnum.UNFROZEN);
        //商户编号
        mainInfoModel.setStoreno(mainInfoModel.getUuid());
        mainInfoModel.setIsralatedcontract(StoreMainInfoEnum.ISRALATEDCONTRACT_NO);
        mainInfoModel.setCreateopetime(DateFormatHelper.getNowTimeStr());
        mainInfoModel.setOpetime(DateFormatHelper.getNowTimeStr());
        //默认为试用期，然后合同上签的试用期为0时，将这个参数修改为正式合同
        mainInfoModel.setIsprobation(StoreMainInfoEnum.IS_PROBATION_YES);
        //默认未注册
        mainInfoModel.setYsuserstate("0");
        mainInfoModel.setStoresubsidyrate("0");
        mainInfoModel.setSettletype("0");
        mainInfoModel.setVersion(0);
        //WANGNING添加默认费率配置
        mainInfoModel.setStorerate(StoreMainInfoEnumConstants.ENUM_RATE_INIT);
        //zml添加支付通道配置
        mainInfoModel.setServiceid("YINSHENG");

        storeMainInfoService.save(mainInfoModel);
        return mainInfoModel;
    }


    @Override
    public ApiResult getChildStoreView(Map<String, Object> mapParams) {
        // 解析map参数
        // 门店uuid
        Object temp = mapParams.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        if (StringUtils.isBlank(storeUuid)) {
            return ApiResult.paramIsNull();
        }

        StoreShopDO shopModel = storeShopService.getByStoreUuid(storeUuid);
        StoreMainInfoDO mainInfoModel = storeMainInfoService.get(storeUuid);
//        if (mainInfoModel != null) {
//            String fullName = storeCategoryService.getCategoryFullName(mainInfoModel.getServcategory(), "-");
//            mainInfoModel.setServCategoryName(fullName);
//        }
       /* if (shopModel != null) {
            String area = provinceService.getAreaName(shopModel.getProvince(), shopModel.getCity(), shopModel.getRegion(), "");
            shopModel.setArea(area);
            BusinessCircleModel businessCircleModel = businessCircleService.getByUuid(shopModel.getBusinessCircleUuid());
            if (businessCircleModel != null) {
                shopModel.setBusinessCircle(businessCircleModel.getBusinessCirName());
            }
        }*/

        Map result = new HashMap();
        result.put("shop", shopModel);
        result.put("mainInfo", mainInfoModel);

        return ApiResult.success(result);
    }

    @Override
    public R getStoreIdAndRuleIdByCounterId(Map<String, Object> params) {

        Map<String, Object> result = storeCheckoutCounterService.getStoreIdAndRuleIdByCounterId(params);

        return R.ok(result);
    }

    @Override
    public R getStoreBankInfo(Map<String, Object> params) {

        Object temp = params.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;

        if (StringUtils.isBlank(storeUuid)) {
            return R.error(JSONUtils.beanToJson(ReturnUtils.paramIsNull()));
        }
        StoreCapitalVirtualAccountDO virtualModel = storeCapitalVirtualAccountService.getStoreCapitalVirtualAccountByStoreUuid(storeUuid);

        return R.ok(JSONUtils.beanToJson(virtualModel));
    }

    @Override
    public R getDistance(Map<String, Object> params) {

        Object temp = params.get("longitude");
        Double longitude = temp != null ? Double.parseDouble(temp.toString()) : null;
        temp = params.get("latitude");
        Double latitude = temp != null ? Double.parseDouble(temp.toString()) : null;
        temp = params.get("shopId");
        String shopId = temp != null ? temp.toString() : null;

        if (longitude == null || latitude == null || shopId == null) {
            return R.error("params is null");
        }
        StoreShopDO storeShopDO = storeShopService.get(shopId);
        double shopLongitude = storeShopDO.getLgt().doubleValue();
        double shopLatitude = storeShopDO.getLat().doubleValue();
        return R.data(DistanceUtils.getDistance(longitude, latitude, shopLongitude, shopLatitude));
    }

    @Override
    public Map<String, String> getStoreShopByCounterId(Map<String, Object> params) {

        Object temp = params.get("counterId");
        String countId = temp != null ? temp.toString() : null;
        Map<String, String> result = new HashMap<>();
        if (StringUtils.isBlank(countId)) {
            return result;
        }
        try {
            StoreCheckoutCounterDO storeCheckoutCounter = storeCheckoutCounterService.get(countId);
            StoreMainInfoDO storeMainInfo = storeMainInfoService.get(storeCheckoutCounter.getStoreuuid());
//            StoreShopDO storeShop = storeShopService.get(storeMainInfo.getUuid());
            result = BeanOrMapConvertUtils.objectToMapWithoutBlank(storeMainInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    @Override
    public R getYsUserInfo(Map<String, Object> params) {

        Object temp = params.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        if (StringUtils.isBlank(storeUuid)) {
            return R.error("商户号为空");
        }
        StoreMainInfoDO storeMainInfo = storeMainInfoService.get(storeUuid);
        Map returnResult = new HashMap();
        returnResult.put("ysUserCode", storeMainInfo.getYsusercode());
        returnResult.put("ysUserStatus", storeMainInfo.getYsuserstate());

        return R.data(returnResult);
    }

    @Override
    public R saveReportedUpdate(Map<String, Object> mapParams) {

        //店铺名称
        Object temp = mapParams.get("storeName");
        String storeName = temp != null ? temp.toString() : null;
        //店铺uuid
        temp = mapParams.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        //分类uuid
        temp = mapParams.get("catetoryUuid");
        String catetoryUuid = temp != null ? temp.toString() : null;
        //门店联系人电话
        temp = mapParams.get("contactman");
        String contactman = temp != null ? temp.toString() : null;
        //人均消费
        temp = mapParams.get("consumption");
        BigDecimal consumption = temp != null ? new BigDecimal(temp.toString()) : null;
        //营业执照复印件
        temp = mapParams.get("bussinessLicensePhoto");
        String bussinessLicensePhoto = temp != null ? temp.toString() : "";
        //法人授权函
        temp = mapParams.get("authorizationLetter");
        String authorizationLetter = temp != null ? temp.toString() : "";
        //轮播图
        temp = mapParams.get("slideshow");
        String slideshow = temp != null ? temp.toString() : "";
        //门头照
        temp = mapParams.get("imageKey");
        String imageKey = temp != null ? temp.toString() : null;
        //内景照
        temp = mapParams.get("imageKeytwo");
        String imageKeytwo = temp != null ? temp.toString() : null;
        //商户类型
        temp = mapParams.get("storeType");
        String storeType = temp != null ? temp.toString() : null;
        //门店详细地址
        temp = mapParams.get("realDetailAddress");
        String realDetailAddress = temp != null ? temp.toString() : null;
        //纬度
        temp = mapParams.get("latitude");
        String latitude = temp != null ? temp.toString() : null;
        //经度
        temp = mapParams.get("longitude");
        String longitude = temp != null ? temp.toString() : null;
        //省
        temp = mapParams.get("province");
        String province = temp != null ? temp.toString() : null;
        //市
        temp = mapParams.get("city");
        String city = temp != null ? temp.toString() : null;
        //区
        temp = mapParams.get("region");
        String region = temp != null ? temp.toString() : null;
        //门店详细地址
        temp = mapParams.get("detailAddress");
        String detailAddress = temp != null ? temp.toString() : null;
        //企业所在省
        temp = mapParams.get("companyInfoProvince");
        String companyInfoProvince = temp != null ? temp.toString() : null;
        //企业所在市
        temp = mapParams.get("companyInfoCity");
        String companyInfoCity = temp != null ? temp.toString() : null;
        //企业所在地址
        temp = mapParams.get("companyInfoAddress");
        String companyInfoAddress = temp != null ? temp.toString() : null;

        if (StringUtils.isBlank(storeName)
                || StringUtils.isBlank(catetoryUuid)
                || consumption == null
                || StringUtils.isBlank(bussinessLicensePhoto)
                || StringUtils.isBlank(imageKey)
                || StringUtils.isBlank(imageKeytwo)
                || StringUtils.isBlank(contactman)
                || StringUtils.isBlank(latitude)
                || StringUtils.isBlank(longitude)
                || StringUtils.isBlank(province)
                || StringUtils.isBlank(city)
                || StringUtils.isBlank(region)
                || StringUtils.isBlank(detailAddress)
                || StringUtils.isBlank(companyInfoProvince)
                || StringUtils.isBlank(companyInfoCity)
                || StringUtils.isBlank(companyInfoAddress)) {
            return R.error("参数缺失");
        }

        StoreMainInfoDO storeMainInfo = storeMainInfoService.get(storeUuid);

        if(!storeMainInfo.getStorename().equals(storeName)){
            //查询门店名称
            Map searchMap = new HashMap();
            searchMap.put("storename", storeName);
            searchMap.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
            List<StoreMainInfoDO> mainInfoModelSearch = storeMainInfoService.list(searchMap);
            if (mainInfoModelSearch.size() != 0) {
                //加锁
                return R.error("店铺名称已存在");
            }
        }

        storeMainInfo.setOpetime(DateFormatHelper.getNowTimeStr());
        storeMainInfo.setStorename(storeName);
        storeMainInfo.setServcategory(catetoryUuid);
        storeMainInfo.setMobile(contactman);
        storeMainInfo.setStoretype(storeType);
        storeMainInfoService.update(storeMainInfo);

        StoreShopDO storeShop = storeShopService.getByStoreUuid(storeUuid);
        storeShop.setConsumption(consumption);
        storeShop.setDoorphoto(imageKey);
        storeShop.setWithinphoto(imageKeytwo);
        storeShop.setSlideshow(slideshow);
        storeShop.setShopname(storeName);
        storeShop.setLat(new BigDecimal(latitude));
        storeShop.setLgt(new BigDecimal(longitude));
        storeShop.setProvince(province);
        storeShop.setCity(city);
        storeShop.setRegion(region);
        storeShop.setChoosedattr(realDetailAddress);
        storeShop.setDetailaddress(detailAddress);
        storeShopService.update(storeShop);

        StoreCapitalVirtualAccountDO storeCapitalVirtualAccount = storeCapitalVirtualAccountService.getStoreCapitalVirtualAccountByStoreUuid(storeUuid);
        storeCapitalVirtualAccount.setStorename(storeName);
        storeCapitalVirtualAccountService.update(storeCapitalVirtualAccount);

        StoreCompanyInfoDO storeCompanyInfo = storeCompanyInfoService.getCompanyInfoByStoreUuid(storeUuid);
        storeCompanyInfo.setAuthorizationletter(authorizationLetter);
        storeCompanyInfo.setContactman(contactman);
        storeCompanyInfo.setProvince(companyInfoProvince);
        storeCompanyInfo.setCity(companyInfoCity);
        storeCompanyInfo.setAddress(companyInfoProvince);

        storeCompanyInfoService.update(storeCompanyInfo);

        CompanyQualificationDO companyQualification = storeCompanyQualificationService.getQualificationByCompanyUuid(storeCompanyInfo.getUuid());
        companyQualification.setBussinesslicensephoto(bussinessLicensePhoto);
        storeCompanyQualificationService.update(companyQualification);
        return R.ok();
    }

    @Override
    public R getShopListByProviderId(Map<String, Object> params) {
        try {
            params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
            // 服务商id
            params.put("chainstoresuuid", FilterContextHandler.getName());
            params.put("sort", "createOpeTime");
            params.put("order", "desc");
            Query query = new Query(params);
            // TODO: 缺少DTO
            /* List<StoreMainInfoDO> list = storeMainInfoService.getStoreListByProviderIdAndAccountId(query);
        int total = storeMainInfoService.getStoreListByProviderIdAndAccountIdCount(query);*/
            List<StoreMainInfoDO> list = storeMainInfoDao.getShopList(query);
            List<StoreMainDTO> dtos = new ArrayList<StoreMainDTO>(list.size());
            for (StoreMainInfoDO storeMainInfoDO : list) {
                switch (storeMainInfoDO.getAuditstatus()) {
                    case StoreMainInfoEnum.AUDIT_UNDONE: {
                        storeMainInfoDO.setAuditstatus("审核中");
                    }
                    break;
                    case StoreMainInfoEnum.BUSINESS_AUDIT_PASS: {
                        storeMainInfoDO.setAuditstatus("业务人员审核通过");
                    }
                    break;
                    case StoreMainInfoEnum.AUDIT_NO_PASS: {
                        storeMainInfoDO.setAuditstatus("审核驳回");
                    }
                    break;
                    case StoreMainInfoEnum.REPORT_UNDONE: {
                        storeMainInfoDO.setAuditstatus("报备失败");
                    }
                    break;
                    case StoreMainInfoEnum.FINANCE_AUDIT_PASS: {
                        storeMainInfoDO.setAuditstatus("财务人员审核通过");
                    }
                    break;
                }
                StoreCompanyInfoDO storeCompanyInfoDO = storeCompanyInfoService.getCompanyInfoByStoreUuid(storeMainInfoDO.getUuid());
                StoreMainDTO storeMainDTO = StoreMainInfoConvert.MAPPER.doToDTO(storeMainInfoDO);
                storeMainDTO.setCompanytype(storeCompanyInfoDO.getCompanytype());
                dtos.add(storeMainDTO);
            }
            int total = storeMainInfoDao.getShopCount(query);
            PageUtils pageUtil = new PageUtils(dtos, total);
            return R.ok().put("page", pageUtil);
        } catch (Exception e) {
            return R.error();
        }
    }

}
